﻿using Eneta.Portal.Common.Dto;

using Microsoft.SharePoint;

namespace Eneta.Portal.Common.Repository
{
    /// <summary>
    /// Repository for tooltips operations.
    /// </summary>
    public class TooltipRepository : BaseRepository
    {
        public TooltipRepository(SPWeb web) : base(web) {}

        /// <summary>
        /// Gets the tooltip by page and area name.
        /// </summary>
        /// <param name="pageName">Name of the page.</param>
        /// <param name="areaName">Name of the area.</param>
        public TooltipDto GetTooltipFor(string pageName, string areaName)
        {
            TooltipDto dto = null;

            var sec = new SPSecurity.CodeToRunElevated(delegate
                       {
                           using(var site = new SPSite(SiteId))
                           using(var web = site.OpenWeb())
                           {
                               dto = GetTooltipFor(web, pageName, areaName);
                           }
                       });
            SPSecurity.RunWithElevatedPrivileges(sec);

            return dto;
        }

        private TooltipDto GetTooltipFor(SPWeb web, string pageName, string areaName)
        {
            var cacheKey = string.Format("Tooltip:{0}:{1}", pageName, areaName);
            var tooltip = GetFromCache<TooltipDto>(cacheKey);
            if (tooltip != null)
                return tooltip;

            var list = web.Lists["Tooltips"];
            
            var queryString = "<Where><And><Eq><FieldRef Name='PageName' /><Value Type='Text'>{0}</Value></Eq>";
            queryString += "<Eq><FieldRef Name='AreaName' /><Value Type='Text'>{1}</Value></Eq></And></Where>";
            queryString = string.Format(queryString, pageName, areaName);

            var items = ExecuteQuery(list, queryString);
            if (items == null)
                return null;
            if (items.Count == 0)
                return null;

            tooltip = CreateTooltip(items[0]);
            SaveToCache(cacheKey, tooltip);
            return tooltip;
        }

        private static TooltipDto CreateTooltip(SPItem item)
        {
            var dto = new TooltipDto
                          {
                              AreaName = item["AreaName"].ToString(),
                              Description = item["Description"].ToString(),
                              Id = item.ID,
                              PageName = item["PageName"].ToString()
                          };
            return dto;
        }
    }
}
